package com.cfl.shiro;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.shiro.util.JdbcUtils;

public class JDBCUtil {

	private static Connection connection;
	
	/**
	 * 连接jdbc
	 * @return
	 */
	public static Connection connectionJDBC()
	{
		try {
			if(connection == null)
			{
				String sql = "jdbc:mysql://localhost:3306/shiro?user=root&password=123456";
				
				// 加载mysql驱动
				Class.forName("com.mysql.jdbc.Driver");

				// 一个Connection代表一个数据库连接
				connection = DriverManager.getConnection(sql);
			}
		} catch (Exception e) {
			connection = null;
		}
		return connection;
	}
	
	/**
	 * 查询
	 * @param sql
	 * @return
	 */
	public static ResultSet executeQuery(String sql)
	{
		try {
			if(connection == null)
			{
				connection = JDBCUtil.connectionJDBC();
			}
			if(connection != null)
			{
				Statement statement = connection.createStatement();
				ResultSet resultSet = statement.executeQuery(sql);
				return resultSet;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
